var listener_service = "/ext/listeners/public/listener.html";
var listener_checkout_service = "/ext/listeners/public/listener_checkout.html";
var listener_email_service = "/ext/listeners/public/listener_email.html";

function process(xml) {
	$(xml).find('total').each(function(){
		$('#nav_tot').html('<span>' + $(this).attr('lines')+': '+$(this).attr('cur')+$(this).attr($(this).attr('price_type_default')) + '</span>');
		$('#trolley_total').html('<span>' + $(this).attr('cur')+$(this).attr($(this).attr('price_type_default')) + '</span>');
  	});

	$(xml).find('part').each(function(){
		var value = (parseFloat($(this).attr($(this).attr('price_type_default'))) * parseInt($(this).attr('quantity'))).toFixed(2);
		$('.pr'+$(this).attr('code')).html('<span>' + $(this).attr('cur')+value + '</span>');
		$('#qu'+$(this).attr('code')).attr('value', parseInt($(this).attr('quantity')));
		$('#qu'+$(this).attr('code')).attr('alt', parseInt($(this).attr('quantity')));
	});

	$("#nav_trolley").queue([]).stop();
 	$("#nav_trolley").unbind().effect("pulsate", {times: 2}, 500);

	var extra_info = '';
	$(xml).find('like').each(function(){
		image = ($(this).attr('image').length>0) ? '<img src="'+$(this).attr('image')+'" alt="'+$(this).attr('name')+'" title="'+$(this).attr('name')+'" width="35" height="35" /> ' : '';
		extra_info += '<li><a href="'+$(this).attr('code')+'">'+image+' '+$(this).attr('name')+'</a></li>';
	});

	if (extra_info.length > 0) {
		extra_info = '<h1>You might also like</h1><ul>'+extra_info+'</ul>';
		if ($(window).scrollTop() > 600) {
			$('#extra_information_box').css('position', 'absolute');
			$('#extra_information_box').css('top', $(window).scrollTop());
		} else {
			$('#extra_information_box').css('position', 'relative');
			$('#extra_information_box').css('top', 0);
		}
		if (($('#extra_information_box').html() != extra_info)) {
			$('#extra_information_box').html(extra_info).fadeTo(0, 0.93).fadeIn();
		}
	} else {
		$('#extra_information_box').fadeOut();
	}
}

//Track mouse movement
/*
var pageX = 0;
var pageY = 0;
jQuery(document).ready(function(){
   $().mousemove(function(e){
   	pageX = e.pageX;
   	pageY = e.pageY;
   }); 
})
*/

function t_qty(product, quantity, express) {
	var allow = true;
	var args = arguments; //AH... do this to avoid scope issues.
	if (express == 0) {
		//if ($('#qu'+product).attr('qty') != quantity) {
		if ($('#qu'+product).attr('alt') != quantity) {
		} else {
			allow = false;
		}
	}

	if (allow) {
		$.post(listener_service, { 'product': product, 'quantity': quantity, 'express': express },
		  function(data){
			process(data);
			checkStock(product);
			// AH20090325
			if(args[3]){ // callback??
				if(typeof args[3] == 'function'){
					args[3](data);
				}
			}
		  }, "xml");
	}
}

function navOptLang(lyrid) {
	$('#'+lyrid).toggle('fast');
	setTimeout("$('#"+lyrid+"').fadeOut('fast');", 5000);
}

function t_like(product, opinion) {
	if (opinion == 1) {
		$(".pref_ok_" + product).fadeTo("fast", 1.0);
		$(".pref_ko_" + product).fadeTo("normal", 0.4);
	} else {
		$(".pref_ok_" + product).fadeTo("normal", 0.4);
		$(".pref_ko_" + product).fadeTo("fast", 1.0);
	}
	$.post(listener_service, { 'product': product, 'opinion': opinion },
	  function(data){
		//
	  }, "xml");
}

//Make pre-FF3 'understand' inline-block (for labels)...
if (document.addEventListener) document.addEventListener('DOMContentLoaded', cmxform, false);
function cmxform() {
	$( '.cmxform' ).hide().end();
	$( '.cmxform' ).find( 'label' ).not( '.nocmx' ).each( function( i ){
		var labelContent = this.innerHTML;
		var labelWidth = document.defaultView.getComputedStyle( this, '' ).getPropertyValue( 'width' );
		var labelSpan = document.createElement( 'span' );
		labelSpan.style.display = 'block';
		labelSpan.style.width = labelWidth;
		labelSpan.innerHTML = labelContent;
		this.style.display = '-moz-inline-box';
		this.innerHTML = '';
		this.appendChild( labelSpan );
	} ).end();
	$( '.cmxform' ).show().end();
}

//Enable pop-up class
$(document).ready(function() {
	//Popups
	if (fancybox_enable) {
		$(".box_pop").fancybox({
			'hideOnContentClick': true,
			'zoomSpeedIn': 100,
			'zoomSpeedOut': 100,
			'overlayShow': true
		});
	}

	//Trolley
	$('.trlA').unbind().click(function(){
		t_qty($(this).attr('rel'), 1, 1);
		return false;
	});
	$('.trlB').unbind().click(function(){
		t_qty($(this).attr('rel'), -1, 1);
		return false;
	});
	$('.trlC').unbind().click(function(){
		t_qty($(this).attr('rel'), 0, 1);
		return false;
	});

	//Left hand side logo rollover link to homepage
	$('#logo').mouseover(function(){
		$('#logo').find('div').html('<span>Home</span>');
	});
	$('#logo').mouseout(function(){
		$('#logo').find('div').html('<span></span>');
	});

	//Email service
	$('.email_service').watch();

	//JS / non-JS formatting
	$('.nonjsshow').hide(); //Hide any stuff only necessary in non-JS browsers
	$('.nonjshide').show(); //Show any JS only stuff
});

/*
 * Postcode lookup service
 * 
 */

var address_find_in_progress = false;
function address_finder(zip, line) {
	if (address_find_in_progress) {
		$('#address_answers').html('<ul id="address_list_options">Searching...</ul>');
	} else {
		if (zip.length > 0) {
			$.post(listener_service, {
				'zip': zip,
				'line': line
			}, function(data){
				address_finder_listener(data);
			}, "xml");
			$('#find_address_button').html('<div class="divAc">Searching...</div>');
			address_find_in_progress = true;
		} else {
			$('#address_answers').html('<ul id="address_list_options">You must enter a postcode!</ul>');
		}
	}
}

function address_finder_listener(xml) {
	$('#find_address_button').html('<span>Find address</span>');
	address_find_in_progress = false;

	var str = '';
	$(xml).find('Data').each(function(){
		str += '<li><a href="javascript:address_finder_fetch(\'' + $(this).find('id').text() + '\');">' + $(this).find('description').text() + '</a></li>';
	});

	if (str.length > 0) {
		$('#address_answers').html('<ul id="address_list_options"><li style="list-style:none;">Please select your address from the list below. If your address is not shown, click the \'Enter Manually\' button.</li>'+str+'</ul>');
	} else {
		$('#address_answers').html('<ul id="address_list_options"><li>No addresses found, please check your postcode and try again or click the \'Enter Manually\' button</li></ul>');
	}
}

function address_finder_fetch(zipid) {
	if (zipid.length > 0) {
		$.post(listener_service, { 'zipid': zipid },
			function(data){
				address_finder_fetch_listener(data);
		}, "xml");
	}
}

function address_finder_fetch_listener(xml) {
	var str = '';
	$(xml).find('Data').each(function(){

		//A whole lot of crazy s**t to sort out what data we may or may not have back. Once again, "woo yay" for jQuery!

		var addr = {};
		addr[$(this).find('organisation_name').text()] = 1;
		addr[$(this).find('department_name').text()] = 1;
		addr[$(this).find('line1').text()] = 1;
		addr[$(this).find('line2').text()] = 1;
		addr[$(this).find('line3').text()] = 1;
		addr[$(this).find('line4').text()] = 1;
		addr[$(this).find('line5').text()] = 1;

		var addr_clean = [];
		jQuery.each(addr, function(index, value) {
			if (index.length > 0) {
				addr_clean.push(index);
			}
		});

		var address = {
			'dad_1house': ((addr_clean[0] != undefined) ? addr_clean[0] : ''),
			'dad_2Aroad': ((addr_clean[1] != undefined) ? addr_clean[1] : ''),
			'dad_2Broad': ((addr_clean[2] != undefined) ? addr_clean[2] : ''),
			'dad_3town': $(this).find('post_town').text(),
			'dad_4county': $(this).find('county').text(),
			'dad_5zip': $(this).find('postcode').text()
		};

		/*
		jQuery.each(address, function(index, value) {
			console.log("index", index, "value", value);
		});
		*/

		jQuery.each(address, function(index, value) {
			$('#'+index).attr('value', value);
		});
		address_finder_hidesearch();

	});

	if (str.length > 0) {
		$('#address_answers').html('<div>'+str+'</div>');
	} else {
		$('#address_answers').html('');
	}
}

function address_finder_hidesearch() {
	$('#address_form').fadeIn('fast');
	$('#dad_1house').focus();
	$('#address_find').hide();
	$('#address_answers').hide();

	address_finder_clean_country();
	address_finder_clean_zip();
}

/*
 * Postcode sanity checking
 * 
 */

var fCountry = 'dad_6country';
var fZip = 'dad_5zip';
var fCountrySelected = null;
var regExp = null;
var zipExp = null;
var clnExp = true;

function address_finder_clean_country() {
	fCountrySelected = document.getElementById(fCountry).options[document.getElementById(fCountry).selectedIndex].value;
	if (fCountrySelected == '1') { //UK
		regExp = "^[A-Z]{1,2}[0-9][0-9A-Z]? [0-9][A-Z]{2}$";
		zipExp = "e.g. TA6 4RN";
		clnExp = false;
	} else if (fCountrySelected == '8') { //NL
		regExp = "^[0-9]{4}[A-Z]{2}$";
		zipExp = "e.g. 2352CZ";
		clnExp = true;
	} else if (fCountrySelected == '9') { //BE
		regExp = "^[0-9]{4}$";
		zipExp = "e.g. 1234";
		clnExp = true;
	} else {
		regExp = null;
		zipExp = null;
		clnExp = true;
	}
	document.getElementById(fZip+'_eg').innerHTML = zipExp;
}

function address_finder_clean_zip() {
	address_finder_clean_country();

	var clean = document.getElementById(fZip).value.toUpperCase();
	if (clnExp) var clean = clean.replace(/\W/, "");
	document.getElementById(fZip).value = clean;

	var regOK = new RegExp(regExp);
	if (regOK.test(clean)) {
		document.getElementById(fZip+'_eg').innerHTML = clean;
		document.getElementById(fZip+'_eg').style.color = '#008040';
		document.getElementById(fZip+'_eg').style.fontWeight = 'bold';
	} else {
		document.getElementById(fZip+'_eg').innerHTML = zipExp;
		document.getElementById(fZip+'_eg').style.color = '#C0C0C0';
		document.getElementById(fZip+'_eg').style.fontWeight = 'normal';
	}
}

function myaccount_details_submit(sig) {
	var msgs = [];
	var ok = true;

	if ($('#ucu_password').attr('value').length >= 6) {
		if ($('#ucu_password').attr('value') != $('#ucu_password_confirm').attr('value')) {
			msgs.push("A valid password and confirm it in the following box.");
			error_highlight('ucu_password', 0);
			error_highlight('ucu_password_confirm', 0);
			ok = false;
		}
	}

	//Check others
	var checks = {};
	checks['ucu_email'] = [/^[a-zA-Z0-9_.-]+([@]{1})[a-zA-Z0-9_.-]+[.][a-zA-Z0-9_.-]+$/i, 'Valid email address'];
	checks['ucu_password'] = [/^[a-zA-Z0-9_\.\?\!\,\-]{6,32}$/i, 'Password (at least 6 characters, can only contain a-z0-9_-.?!,)'];
	checks['ucu_title'] = [/^[a-zA-Z0-9\. ]{2,10}$/i, 'Title']; 
	checks['ucu_firstname'] = [/^[a-zA-Z0-9\. -\']{2,32}$/i, 'Firstname'];
	checks['ucu_lastname'] = [/^[ a-zA-Z0-9.\'-]{2,32}$/i, 'Surname'];
	jQuery.each(checks, function(k, v){
		var ans = checks[k][0].exec($('#' + k).attr('value'));
		if (ans === null) {
			error_highlight(k, 0);
			msgs.push(checks[k][1]);
			ok = false;
		} else {
			error_highlight(k, 1);
		}
	});

	if (!ok && (msgs.length > 0)) {
		var msgs_build = 'Please check the information you have entered in the following boxes:\n\n';
		for (var i=0; i<msgs.length; i++) msgs_build += "* " + msgs[i] + "\n";
		alert(msgs_build);
	}

	if (sig && ok) {
		$('#myaccount_details_form').submit();
	}
	
	return ok;
}

//checkout.html
function delivery_change(code, tot, discount) {
	var delivery_price = $('#'+code).attr('alt');
	var total_price = parseFloat(delivery_price) + parseFloat(tot) - parseFloat(discount);

	$('.delivery_price').html(number_format(delivery_price, 2, '.', ','));
	$('.total_price').html(number_format(total_price, 2, '.', ','));

	//Style chosen delivery time info 
	$('.dlvOptTimes').css({'font-size':'1em', 'border':'none', 'padding':'0.2em', 'margin-top':'0.2em'});
	$('#dot'+code).css({'font-size':'1.3em', 'border-bottom':'2px solid red'});
}

//paySwitch is a NL only function
function paySwitch(to) {
	// uncheck all payment options
	$('ol#paymentMethods input').attr('checked', null);
	if($('ol#paymentMethods input#' + to)[0]){ // check the selected payment option
		$('ol#paymentMethods input#' + to).attr('checked', 'checked');
		if(to == 'iCARDS'){ // only show card options for iCards
			$('#cardOptions').show();
		}else{ 
			$('#cardOptions').hide();
		}
	}
	/*
	if (to == 'iDEAL') {
		//$('#iDEAL').attr('checked', 'checked'); //this style?
		document.getElementById('iDEAL').checked = true;
		document.getElementById('iCARDS').checked = false;
		document.getElementById('iACCOUNT').checked = false;
		
	} else if (to == 'iACCOUNT') {
		document.getElementById('iDEAL').checked = false;
		document.getElementById('iCARDS').checked = false;
		document.getElementById('iACCOUNT').checked = true;
		$('#cardOptions').hide();
	} else {
		document.getElementById('iDEAL').checked = false;
		document.getElementById('iCARDS').checked = true;
		document.getElementById('iACCOUNT').checked = false;
		$('#cardOptions').show();
	}
	*/
}

function checkout_progression_back(stage) {
	if (stage === 1) { //Back to delivery (from payment)
		$('#tabsEx1 > ul').tabs('select', 0);
		$('#tabsEx1 > ul').tabs('disable', 1);
	} else {
		alert('Doh.');
	}
}

var order_check_busy = false;

function checkout_progression_advance(stage) {

if (order_check_busy == false) {

	window.scrollTo(0, 0);

	if (stage === 1) { //Check delivery
		//Do checks
		
		order_check_busy = true;
		
		var allowSubmit = true;

		if (document.getElementById('d'+delivery_code_collect)) {
			if (document.getElementById('d'+delivery_code_collect).checked) {
				//Check a sales-counter has been chosen
				allowSubmit = false; //Do not allow submit if no sales-counter chosen
				var i = document.getElementById('chk_delv_pickup').selectedIndex;
				if (i > 0) {
					var ii = document.getElementById('chk_delv_pickup').options[document.getElementById('chk_delv_pickup').selectedIndex].value;
					if (ii.length > 0) {
						//Looks good enough for now
						allowSubmit = true;
					}
				}
				
				error_highlight('chk_delv_pickup', 1);
				
				if (!allowSubmit) {
					alert("Choose the branch you want to pick your order up from!");
					error_highlight('chk_delv_pickup', 0);
					$('#chk_delv_pickup').effect("shake");
				}
			}
		}

		if (allowSubmit) {
			//Advance tab, if OK
			$('#tabsEx1 > ul').tabs('enable', 1);
			$('#tabsEx1 > ul').tabs('select', 1);
		}
		
		order_check_busy = false;
		
	}
	else 
		if (stage === 2) { //Check payment
			//Do checks
			
			//var check_card_details = true;
			
			/*
			//If card-direct method is chosen
			if (country_default == 'NL') {
				if ($('#cardOptions').css('display') != 'block') {
					check_card_details = false;
				}
			}
			
			if($('#PayPal').is(':checked')){
				// Change action of form...
				$('#conf_order_button_nonjs').val('Please wait...');
				$('#checkout_form_data').attr('action', 'checkout_paypal.html').unbind('submit').submit();
				return false;
			}
			*/
			var payment_errors = false;
			
			if ($('#iCARDS').is(':checked') || !$('#iCARDS')[0]) {
			
				//Check card details
				var checks = {};
				checks['card_no'] = /^[0-9 ]{10,}$/i;
				checks['card_name'] = /^[a-zA-Z0-9\'\.\, \-]{1,32}$/i;
				checks['card_issue'] = /^[0-9]{0,2}$/i;
				checks['card_security_number'] = /^[0-9]{3,4}$/i;
				jQuery.each(checks, function(k, v){
					var ans = checks[k].exec($('#' + k).attr('value'));
					if (ans === null) {
						error_highlight(k, 0);
						payment_errors = true;
					}
					else {
						error_highlight(k, 1);
					}
				});
				
				//Check card expiry
				var selected_exp_month = parseFloat($("#card_end_m").fieldValue());
				var selected_exp_year = parseFloat($("#card_end_y").fieldValue());
				var date_exp_ok = true;
				if (selected_exp_year == date_year) {
					if (selected_exp_month < date_month) {
						date_exp_ok = false;
					}
				}
				else 
					if (selected_exp_year < date_year) {
						date_exp_ok = false;
					}
				
				if (date_exp_ok) {
					error_highlight('card_end_y', 1);
					error_highlight('card_end_m', 1);
				}
				else {
					payment_errors = true;
					error_highlight('card_end_y', 0);
					error_highlight('card_end_m', 0);
				}
				
				//Check card start
				var selected_start_month = parseFloat($("#card_start_m").fieldValue());
				var selected_start_year = parseFloat($("#card_start_y").fieldValue());
				var date_start_ok = true;
				
				if (isNaN(selected_start_month) || isNaN(selected_start_year)) {
				}
				else {
					if (selected_start_year == date_year) {
						if (selected_start_month > date_month) {
							date_start_ok = false;
						}
					}
					else 
						if (selected_start_year > date_year) {
							date_start_ok = false;
						}
				}
				
				if (date_start_ok) {
					error_highlight('card_start_y', 1);
					error_highlight('card_start_m', 1);
				}
				else {
					payment_errors = true;
					error_highlight('card_start_y', 0);
					error_highlight('card_start_m', 0);
				}
				
			}
			
			if (!payment_errors) {
				order_check_busy = true;
				$('#conf_order_button').html('Please wait...');
				$('#messages_to_show').html('<div class="subdepartment_table"><h4>Please wait while we check your payment details...</h4></div>');
				$('#messages_to_show').fadeIn();
				$('#back_order_button').fadeOut();

//Comment this out to turn off AJAX option
				$('#checkout_form_data').ajaxForm({
					dataType: 'xml',
					success: process_order
				});
//...and uncomment this
//$('#confirm').attr({'value':'1'});

				$('#checkout_form_data').submit();
			}
		}
		else { //Unknown
			alert('Doh.');
		}
	
} //order_check_busy

}

function process_order(xml){
	$(xml).find('error').each(function(){
		if($(this).attr('field') != 'redirect_url'){
			error_highlight($(this).attr('field'), 0);
			order_check_busy = false;
			$('#conf_order_button').html('<span>Try and confirm your order again</span>');
		}
	});
	
	var messages_to_show = '';
	var $errors = $(xml).find('error');
	var extra = {};
	
	$(xml).find('extraaction').each(function(){
		extra[$(this).attr('action')] = $(this).attr('data');
	});
	$(xml).find('message').each(function(){
		error_highlight($(this).attr('field'), 0);
		messages_to_show += '<li>' + $(this).attr('field') + '</li>';
	});
	if (messages_to_show.length > 0) {
		$('#messages_to_show').hide();
		$('#messages_to_show').html('<div class="subdepartment_table"><h4>Please check your payment details</h4><ul>' + messages_to_show + '</ul></div>');
		$('#messages_to_show').fadeIn();
	}
	else {
		$('#messages_to_show').fadeOut();
		$('#messages_to_show').html('');
	}
	
	var order_uid = false;
	var redirect_method = false;
	$(xml).find('detail').each(function() {
		order_uid = $(this).attr('uid');
	});

	if (order_uid == false) {
		if ($errors[0]) { // contains error node
			if ($($errors[0]).attr('field') == 'redirect_url' || $($errors[1]).attr('field') == 'redirect_url') { // redirect method
				var link = '<li>To continue to payment options, please click: <div class="divAc"><a class="b2" href="' + extra["RedirectURL"] + '"><span>Proceed</span></a></div></li>';
				$('#messages_to_show .subdepartment_table ul').append(link);
				redirect_method = true;
				document.location.href = extra["RedirectURL"];
			} else if ($($errors[0]).attr('field') == '3DSecure') {
				var html3d = '<form method="post" action="' + extra["3DSecureURL"] + '" id="form3d">';
				//var html3d = '<form method="post" action="' + extra["3DSecureURL"] + '" id="form3d" target="iframe3d">'; // IFRAME VERSION
				html3d += '<input type="hidden" name="PaReq" value="' + extra["3DSecurePaReq"] + '" />';
				html3d += '<input type="hidden" name="TermUrl" value="' + extra["3DSecureTermUrl"] + '" />';
				html3d += '<input type="hidden" name="MD" value="' + extra["3DSecureMD"] + '" />';
				html3d += '<input type="hidden" name="MD" value="' + extra["3DSecureMD"] + '" />';
				html3d += '<div class="subdepartment_table"><p>We are now going to forward you to your own card issuer for identification. If your browser does not start loading the page, press the button you see just below.</p><p>After you sucessfully identify yourself you will be sent back to us where we will then complete your order.</p><div style="text-align: center; padding: 2em; font-weight: bold;"><input type="submit" class="b2" value="Proceed through your bank\'s security check" /></div></div>';
				html3d += '</form>';
/*
				 // IFRAME VERSION
				 var iframe3d = '<iframe name="iframe3d" id="iframe3d"></iframe>';
				 $('#site_center').css({position:'relative'}).append(iframe3d);
				 $('#iframe3d').css({position:'absolute', left: 0, backgroundColor: '#ffffff', border: '1px solid #062B5F', height: '454px', left: '0.7em', top: '2.25em', width: '672px'});
*/
				//$('body').append(html3d);
				$('#messages_to_show').html(html3d);
				$('#form3d').submit();
			}
		}
	}

	if (order_uid != false) {
		$('#sucessful_order_uid').html(order_uid);

		$('#tabsEx1 > ul').tabs('enable', 2);
		$('#tabsEx1 > ul').tabs('select', 2);

		$('#fragment-1').html('Complete');
		$('#fragment-2').html('Complete');
		$('#tabsEx1 > ul').tabs('disable', 0);
		$('#tabsEx1 > ul').tabs('disable', 1);

		$('#nav_tot').html('');
		$('#trolley_total').html('');
	} else {
		if(!redirect_method){
			$('#back_order_button').fadeIn();
			order_check_busy = false;
			$('#conf_order_button').html('<span>Try and confirm your order again</span>');
		}
	}
}

function error_highlight(id, ok) {
	if (ok == 0) {
		$('#' + id).css({
			border: '1px solid #ff0000',
			'font-weight': 'bold',
			color: '#ff0000'
		});
	} else {
		$('#' + id).css({
			border: '1px solid #34A0E0',
			'font-weight': 'normal',
			color: '#6C6C6C'
		});
	}
}

function number_format( number, decimals, dec_point, thousands_sep ) {
	var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
	var d = dec_point == undefined ? "." : dec_point;
	var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
	var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

jQuery.fn.fadeToggle = function(speed, easing, callback) {
   return this.animate({opacity: 'toggle'}, speed, easing, callback);

};

function bookmark_create(title, url) {
	if (window.sidebar) { //mozilla
		window.sidebar.addPanel(title, url,"");
	} else if (window.external) { //ie
		window.external.AddFavorite(url, title);
	} else if (window.opera && window.print) { //opera
		return true;
	}
}
function bookmark_show(title, url, colour) {
	var link_html = ' <a href="javascript:bookmark_create(\''+title+'\', \''+url+'\');" class="b2" style="background-color: #'+colour+'; border-color: #'+colour+';"><span>Bookmark this page</span></a>';
	if (window.external) {
		document.write(link_html);
	} else  if (window.sidebar) {
		document.write(link_html); 
	} else if (window.opera && window.print) {	
		document.write(link_html);
	}	
}

//Stock qty helper.
function checkStock(product) {
	var stock1 = $('.sttCa', $('#qu'+product).parent().parent());
	var stock2 = $('.sttCb', $('#qu'+product).parent().parent());
	var qty = parseInt($('#qu' + product).val(), 10);
	if(qty > parseInt(stock1.text(), 10)){
		stock1.addClass('stockover');
	}else{
		stock1.removeClass('stockover');
	}
	if(qty > parseInt(stock2.text(), 10)){
		stock2.addClass('stockover');
	}else{
		stock2.removeClass('stockover');
	}
}

var autoCompLoaded = false;
var autoCompLoad = function(){
	autoCompLoaded = true;
	$('#search').tscjs_searchAutoComp({
		url: JSCONST.searchUrl + '/AutoComp',
		begin_callback: function(){
			$('#search').addClass('searching');
		},
		results_callback: function(json, page, $el){
			setTimeout(function(){
				$('#search').removeClass('searching');
			}, 1000);
			if(json && json.parts.length > 0){
				$('#autocomp').show();
				tscJs.searchDisplay.displayAutoComp(json, page, $el);
			}else{
				$('#autocomp').hide();
			}
		},
		base: JSCONST.base,
		lang: JSCONST.lang
	});
};

/**
 * Virtual Catalogue Auto-loader
 * Lazyloads the virtual catalogue constants (base specific) then loads the object itself.
 */
var vcatLoad = function(callback){
	if(typeof JSCONST.vcat == 'undefined'){
		$.getScript(JSCONST.vcatPath + '/config.html', function(){
			$.getScript(JSCONST.vcatPath + JSCONST.vcat.catJs, function(){
				callback(JSCONST.vcat);
			});
		});
	}else{
		if(typeof callback == 'function'){
			callback(JSCONST.vcat);
		}
	}
};

$(document).ready(function(){
	$('a.trlA').each(function(){
		checkStock($(this).attr('rel'));
	});
	if($('#search')[0]){ // non-ssl
		if($.tscJs && $.tscJs.search){ // search library already loaded?
			autoCompLoad();
		}else{
			$('#search').focus(function(){ // load search library when search field focussed
				if(!autoCompLoaded){ // only if not already loaded
					$.getScript(JSCONST.searchJs, autoCompLoad);
				}
			});
		}
	}else{
		$('#autocomp_form').submit(function(){
			document.location.href = $(this).attr('action') + '?searchstr=' + $('#autocomp_form .t').val();
			return false;
		});
	}

	/**
	 * Virtual Catalogue Instantiation
	 * If enabled, hook on to catalogue page link click event and auto load virtual catalogue 
	 */
	if(typeof JSCONST == 'object' && typeof JSCONST.catEnabled != 'undefined' && JSCONST.catEnabled){

    vcatLoad(function(cfg){
      $('.cat_page_no').each(function(){
        var new_elm = $(this).clone();
        new_elm.css('padding-left', '5px');
        new_elm.html($('<img>', {src: cfg.catPrefix+'/'+$(this).attr('title')+cfg.catThumbPostfix}));
        $(this).parent().parent().find('.imageBxCont').append(new_elm);
      });
      $('.cat_page_no').css('cursor', 'pointer');

  		$('.cat_page_no').click(function(){
  			var a = this;
  			vcatLoad(function(cfg){
  				var pagenum = $(a).attr('title');
  				tscJs.catalogue({
  					page: pagenum,
  					pageImagePrefix: cfg.catPrefix,
  					numPages: cfg.catNumPages,
  					searchUrl: JSCONST.searchUrl,
  					overlayColour:cfg.overlayColour,
  					overlayOpacity: cfg.overlayOpacity,
  					onProductClick: function(product){
  						setTimeout(function(){
  							location.href = cfg.catLinkPrefix + product.code;
  						}, 0);
  					}
  				});
  			});
  			return false;
  		});

    });

	}
});

//Email service
(function($) {
	$.Watch = function(el, options) { // singleton
		$.Watch.ts.add(el, options);
	};
	$.fn.watch = function(options) {
		return this.each(function(){
			$.Watch.ts.add(this, options);
		});
	};
	$.Watch.ts = {
	    options: {
			url: listener_email_service
	    },
		slidecall: 0,
		add: function(el, options){
			if(options) $.extend(this.options, options);
			var that = this;
			$(el).unbind().blur(function(){
				if($(el).val().match(/^[a-zA-Z0-9_.-]+([@]{1})[a-zA-Z0-9_.-]+[.][a-zA-Z0-9_.-]+$/i)){
					$.post(that.options.url, {email:$(el).val()});
				}
			});
		}
	}
})($);

// Tooltips Class
(function($) {
	$.TSTip = function(options){
		$.TSTip.ts.go(options);
	};
	$.TSTip.ts = {
	    options: {
			topOffset: 15, // default top offset
			leftOffset: 15, // default left offset
			domid: 'tstip', // domid of tip container
			innerclass: 'tipinner', // css class name of inner container (the div that holds text)
			offsetUnit: 'px', // default offset unit (usually px),
			tipselector: 'a.b',
			width:false
	    },
		go: function(options){
			var that = this;
			$('body').append('<div id="' + this.options.domid + '"><div class="tipinner"></div></div>'); // append tip node
			if(options) $.extend(this.options, options); // merge options
			$('body').unbind('mousemove').mousemove(function(evt){
				that.getpos(evt);
			});
			if(this.options.width){
				$('#' + this.options.domid).css({width:this.options.width});
			}
		},
		getpos: function(evt){
			if(evt){
				try{
					$el = $(evt.target);
					if($el.is(this.options.tipselector)){
						//
					}else if($el.parent().is(this.options.tipselector)){
						$el = $el.parent();
					}else{
						$('#' + this.options.domid).hide();
						return false;
					}
					var tipwidth = $('#' + this.options.domid).width();
					var tipheight = $('#' + this.options.domid).height();
					var rightedge = (evt.pageX + this.options.leftOffset + tipwidth);
					var bottomedge = (evt.pageY + this.options.topOffset + tipheight);
					var mainwidth = $(window).width();
					var mainheight = $(window).height();
					var _left = (evt.pageX + this.options.leftOffset);
					var _top = (evt.pageY + this.options.topOffset);
					if(rightedge > (mainwidth-this.options.leftOffset)){
						_left = _left - (this.options.leftOffset*2) - tipwidth;
					}
					if(bottomedge > mainheight){
						_top = _top - (this.options.topOffset*2) - tipheight;
					}
					var poscss = {left:_left + this.options.offsetUnit, top:_top + this.options.offsetUnit}; // set tip position based on element
					var title = $el.attr('name') || $el.attr('title') || $el.text() || $el.attr('href') || $el.val()  || ''; // attempt to get text for tooltip
					$('#' + this.options.domid + ' .' + this.options.innerclass).html(title); // display text inside inner container
					if($el.attr('title')){ // temporarily remove title attribute
						$el.attr('name', $el.attr('title'));
						$el.attr('title','').mouseout(function(){
							$(this).attr('title',$(this).attr('name'));
						});
					}
					$('#' + this.options.domid).show().css(poscss); // show tip and apply position css
				}catch(e){}
			}
		}
	}
})($);


//Google Analytics
function load_ga() {
	var gaJsHost = document.location.protocol == "https:" ? "https://ssl." : "http://www.";
	var s = document.createElement('script');
	s.src = gaJsHost + "google-analytics.com/ga.js";
	s.type = "text/javascript";
	document.getElementsByTagName("head")[0].appendChild(s);
	var i = 0;
	run_ga();
	function run_ga() {
		if (typeof _gat == "object") {
			var pageTracker = _gat._getTracker(urchin_uid);
			pageTracker._initData();
			pageTracker._trackPageview();
		} else if (i < 20) {
			i++;
			setTimeout(run_ga, 500);
		}
	}
}
